﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using StockFinder.IBD;
using StockFinder.Model;
using StockFinder.StockLists.Exchanges;
using StockFinder.StockLists;
using StockFinder.YahooFinance;
using System.Configuration;
using System.Diagnostics;

namespace StockFinder.Consoles.YahooFinancePricesDownloader
{
    class Program
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

        const string DOWNLOAD_DIRECTORY_KEY = "DownloadDirectory";

        static void Main(string[] args)
        {
            Log.Info("Starting up");

            var downloadDirectory = ConfigurationManager.AppSettings[DOWNLOAD_DIRECTORY_KEY];
            if (string.IsNullOrEmpty(downloadDirectory))
            {
                Log.Error("No appsetting for 'DownloadDirectory' in app.config, quitting");
            }
            else
            {
                var downloader = new YahooFinanceOnlineStockPriceHistoryDownloader();
                var stockList = new MarketSmithAndNasdaqOnlineYahooFinanceOnlineStockList() { LoadPrices = false };
                var stopWatch = new Stopwatch();
                var counter = 0;
                var stockListCount = stockList.Count;

                Log.DebugFormat("{0} stocks to download", stockListCount);
                
                stopWatch.Start();

                foreach (var item in stockList)
                {
                    counter++;

                    try
                    {
                        downloader.DownloadAndSaveSymbolPricesCsv(item, DateTime.Today.AddYears(-40), DateTime.Today, downloadDirectory);
                    }
                    catch (Exception exception)
                    {
                        Log.Error(exception);
                    }

                    Log.DebugFormat("{0}% completed", Math.Round(((double)counter / (double)stockListCount)*100,2));
                }

                stopWatch.Stop();
                Log.DebugFormat("Took {0:1} (m:s) to complete", stopWatch.Elapsed.Seconds, stopWatch.Elapsed.Milliseconds);
            }            
        }
    }
}
